package com.kokotchy.tuxcontrol;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * Thread used to check if the connection to the given server is possible
 * 
 * @author $Author: kokotchy $
 * @version $Revision: 18 $
 * 
 */
public class TuxConnection extends Thread {

	/**
	 * TAG for debugging
	 */
	private static final String TAG = "TuxConnection";

	/**
	 * Handler used for communication with main thread
	 */
	private Handler mHandler;

	/**
	 * Host to test
	 */
	private String mHost;

	/**
	 * Port to test
	 */
	private int mPort;

	/**
	 * Create a new TuxConnection with the handler to communicate with the main
	 * thread, and host and port to test
	 * 
	 * @param handler
	 *            Handler for communication with the main thread
	 * @param host
	 *            Host to test
	 * @param port
	 *            Port to test
	 */
	public TuxConnection(Handler handler, String host, int port) {
		Log.i(TAG, "Creation of TuxConnection");
		mHandler = handler;
		mHost = host;
		mPort = port;
	}

	@Override
	public void run() {
		Log.i(TAG, "Starting thread...");
		String pattern = "http://%s:%d/0/server/version?empty";
		try {
			URL url = new URL(String.format(pattern, mHost, mPort));
			URLConnection connection = url.openConnection();

			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(new InputSource(connection
					.getInputStream()));
			Node root = document.getFirstChild();
			Node result = root.getLastChild();
			if (result.getNodeName().equals("result")) {
				String resultValue = result.getFirstChild().getNodeValue();
				if (resultValue.equals("Success")) {
					Log.i(TAG, "Success!");
					success();
				} else {
					Log.i(TAG, "Isn't Success but " + resultValue);
					failure();
				}
			} else {
				Log.i(TAG, "It isn't result but " + result.getNodeName());
				failure();
			}
		} catch (MalformedURLException e) {
			failure(e);
		} catch (ParserConfigurationException e) {
			failure(e);
		} catch (IOException e) {
			failure(e);
		} catch (SAXException e) {
			failure(e);
		}
	}

	/**
	 * Failure when attempt to connect, no reason
	 */
	private void failure() {
		sendMessage(false);
	}

	/**
	 * Failure when attempt to connect with the given exception
	 * 
	 * @param e
	 *            Exception
	 */
	private void failure(Exception e) {
		sendMessage(false);
	}

	/**
	 * Send the result to the main thread
	 * 
	 * @param result
	 *            If the connection is possible or not
	 */
	private void sendMessage(boolean result) {
		Message msg = mHandler.obtainMessage();
		Bundle b = new Bundle();
		b.putBoolean("connected", result);
		msg.setData(b);
		mHandler.sendMessage(msg);
	}

	/**
	 * Success connection
	 */
	private void success() {
		sendMessage(true);
	}
}
